package com.fz.song.controller;

import com.fz.song.common.Constants;
import com.fz.song.enums.ExceptionEnum;
import com.fz.song.exception.CustomException;
import com.fz.song.pojo.SysResource;
import com.fz.song.pojo.SysRoleResource;
import com.fz.song.pojo.SysRoleUser;
import com.fz.song.pojo.SysUser;
import com.fz.song.resolver.MyHandlerException;
import com.fz.song.service.ResourceService;
import com.fz.song.service.RoleService;
import com.fz.song.service.UserService;
import com.fz.song.util.CookieUtil;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.fz.song.util.CookieUtil.getMD5;

/**
 * Created by sfz on 2017/8/23.
 */

@Controller
public class MainController extends BaseController {

    private static final Logger logger = LogManager.getLogger(MainController.class);

    @Autowired
    public UserService userService;
    @Autowired
    public RoleService roleService;
    @Autowired
    public ResourceService resourceService;

    @RequestMapping("/")
    public String defaultMapping(HttpServletRequest request, HttpServletResponse response) {

        return "redirect:/index";
    }

    @RequestMapping("index")
    public String index(HttpServletRequest request, HttpServletResponse response) throws CustomException {
        return "index";
    }

    @RequestMapping("login")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        return "login";
    }

    @RequestMapping("userlogin")
    @ResponseBody
    public Object userlogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        //获取session中的验证码
        String validate_code = (String) session.getAttribute(Constants.VALIDATE_CODE);
        //用户名
        String username = request.getParameter("username").trim();
        //密码
        String password = request.getParameter("password").trim();
        //验证码
        String vcode = request.getParameter("vcode").trim();
        //记住密码
        String remember = request.getParameter("remember");
        //校验数据
        if (username == null || "".equals(username)) {
            ExceptionEnum usernameIsNull = ExceptionEnum.USERNAME_IS_NULL;
            throw new CustomException(usernameIsNull.getCode(), usernameIsNull.getMessage());
        }
        if (password == null || "".equals(password)) {
            ExceptionEnum pwdIsNull = ExceptionEnum.PWD_IS_NULL;
            throw new CustomException(pwdIsNull.getCode(), pwdIsNull.getMessage());
        }
        if (vcode == null || "".equals(vcode)) {
            ExceptionEnum validateCodeIsNull = ExceptionEnum.VALIDATE_CODE_IS_NULL;
            throw new CustomException(validateCodeIsNull.getCode(), validateCodeIsNull.getMessage());
        }

        if (validate_code == null || "".equals(validate_code)) {
            ExceptionEnum validateExpire = ExceptionEnum.VALIDATE_EXPIRE;
            throw new CustomException(validateExpire.getCode(), validateExpire.getMessage());
        }

        if (!validate_code.equals(vcode)) {
            ExceptionEnum validateError = ExceptionEnum.VALIDATE_ERROR;
            throw new CustomException(validateError.getCode(), validateError.getMessage());
        } else {
            session.removeAttribute(Constants.VALIDATE_CODE);
        }

        Map<String, Object> map = userService.userLogin(username, password);
        Boolean status = (Boolean) map.get("status");
        String message = (String) map.get("message");

        if (status) {
            //处理登录逻辑
            //1.在session存储登录标记
            SysUser sysUser = (SysUser) map.get("obj");

            loginAfter(request, response, session, sysUser);

            //记住我
            if ("true".equals(remember)) {
                //存储cooks
                CookieUtil.saveCookie(sysUser.getLoginname(), sysUser.getPassword(), response);
            } else {
                //清除cooks
                CookieUtil.clearCookie(response);
            }
            return result(1, message);
        } else {
            return result(0, message);
        }
    }

    public void loginAfter(HttpServletRequest request, HttpServletResponse response, HttpSession session, SysUser sysUser) {
        session.setAttribute(Constants.LOGIN_USER, sysUser);
        session.setMaxInactiveInterval(60 * 30);
        //处理权限信息

        //加载我的待办

        //加载我的菜单
        Integer userid = sysUser.getSysid();
        //获取我的角色
        List<SysResource> userRoles = roleService.getMyResource(userid);

        List<SysResource> onelist = new ArrayList<SysResource>();
        //定义一个一级目录
        List<SysResource> twolist = new ArrayList<SysResource>();
        //定义一个二级目录

        for (SysResource resource : userRoles) {
            String type = resource.getType();
            if (Constants.MENU_MODULE.equals(type)) {
                onelist.add(resource);
            } else {
                twolist.add(resource);
            }
        }

        for (SysResource one : onelist) {
            Integer sysid = one.getSysid();
            for (SysResource two : twolist) {
                Integer pid = two.getPid();
                if (sysid == pid) {
                    one.getChilds().add(two);
                }
            }
        }
        session.setAttribute("menuinfo", onelist);

        //加载我的消息
    }

    @RequestMapping("userlogout")
    public Object userlogout(HttpServletRequest request, HttpServletResponse response, String loginname, String password) throws CustomException {
        HttpSession session = request.getSession();
        session.removeAttribute(Constants.LOGIN_USER);
        CookieUtil.clearCookie(response);
        return "redirect:/login";
    }

    @RequestMapping("homepage")
    public Object homepage(HttpServletRequest request, HttpServletResponse response, String loginname, String password) throws CustomException {
        ExceptionEnum test = ExceptionEnum.TEST;
        if (true) {
            throw new CustomException(test.getCode(), test.getMessage());
        }
        return "homepage";
    }
}
